﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using dacli.modelos.dao;
using System.Data.SqlClient;

namespace dacli.pantallas
{
    public partial class Catalogo : Form
    {
        public const int SINRESULTADOS = -1;
        public int resultado;
        public string campo;
        private string tabla;
        private Conexion conexion;
        private DataTable dataTable;
        private BindingSource bindingSource;

        private void mostrarGrilla()
        {
            dataTable.Clear();
            bindingSource = new BindingSource();
            string sql = "SELECT * FROM " + tabla + this.getFiltro();
            SqlDataAdapter MyDA = conexion.consultarAdapter(sql);
            MyDA.Fill(dataTable);
            bindingSource.DataSource = dataTable;
            grilla.DataSource = bindingSource;
        }

        private string getFiltro()
        {
            if (txtFiltro.Text == "") {
                return "";
            }
            else {
                return " WHERE " + this.campo + " LIKE '%" + txtFiltro.Text + "%'";
            }
       }

        public Catalogo(string tabla, string campo)
        {
            
            InitializeComponent();
            this.tabla = tabla;
            conexion = new Conexion();
            dataTable = new DataTable();
            this.campo = campo;
            grilla.ReadOnly = true;
            resultado = SINRESULTADOS;
            mostrarGrilla();
            grilla.Columns[0].Visible = false;
            grilla.Columns[1].Width = 500;
        }

        private void grilla_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void grilla_DoubleClick(object sender, EventArgs e)
        {
            try
            {
                this.resultado = Convert.ToInt32(grilla[0, grilla.CurrentCell.RowIndex].Value.ToString());
            }
            catch (Exception ex) {
                Console.WriteLine(ex);
            }
            
            this.Close();
        }

        private void txtFiltro_TextChanged(object sender, EventArgs e)
        {
            this.mostrarGrilla();
        }
    }
}

